package it.fc.auth;

import fc.utils.FcCostanti;
import it.fc.bean.UserBean;

import java.util.Map;

import org.apache.log4j.Logger;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginIntercept extends AbstractInterceptor {

    private static final long serialVersionUID = 5630249967151890594L;
    private static Logger     log              = Logger.getLogger(LoginIntercept.class);

    @Override
    public void init() {
        log.info("---------------Init LoginInterceptor-------------");
    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {

        UserBean user = (UserBean) getSession().get(FcCostanti.SESSION_USER);

        if (user != null) { // utente loggato
            if (invocation.getProxy().getNamespace().endsWith(FcCostanti.ADMIN_TARGET) && !user.isUserInRole(FcCostanti.ROLE_ADMIN)) {
                return FcCostanti.LOGIN_TARGET;
            } else {
                return invocation.invoke();
            }
        } else {
            return FcCostanti.LOGIN_TARGET;
        }
    }

    @SuppressWarnings("unchecked")
    private Map<String, Object> getSession() {
        return ActionContext.getContext().getSession();
    }

    @Override
    public void destroy() {
        log.info("---------------Destroy LoginInterceptor-------------");
    }
}
